package service

import (
	"errors"
	"gorm.io/gorm"
	"tdy-backend/app/core/service"
	"tdy-backend/app/panoramic/dto"
	"tdy-backend/app/panoramic/model"
	"tdy-backend/global"
	"tdy-backend/pkg/paginator"
)

type WorksService struct {
	service.BaseService
}

//新增作品
func (o *WorksService) Add(param dto.WorksCommitDto) (bool, error) {
	works := model.Works{}
	db := o.DB

	worksInfo := db.Where("title=?", param.Title).First(&works)

	if !errors.Is(worksInfo.Error, gorm.ErrRecordNotFound) {
		return false, errors.New("作品名称重复，请核实")
	}
	works.Title = param.Title
	works.Status = param.Status
	works.Cover = param.Cover
	works.MemberId = o.MemberInfo.ID
	create := db.Create(&works)
	if create.Error != nil {
		return false, errors.New("作品创建失败")
	}
	groupService := GroupService{}
	groupService.MakeORM(o.DB).MakeMemberInfo(o.MemberInfo)
	group, err := groupService.Add(&dto.GroupAddDto{Title: "默认分组", WorksId: works.ID, IsDefault: 1})
	if err != nil {
		return false, err
	}
	param.SceneParam.GroupId = group.ID
	param.SceneParam.WorksId = works.ID
	sceneService := SceneService{}
	sceneService.MakeORM(o.DB).MakeMemberInfo(o.MemberInfo)
	err = sceneService.JoinTo(param.SceneParam)
	if err != nil {
		return false, err
	}
	return true, nil
}

//删除作品
func (o *WorksService) Delete(param *dto.WorksDeleteDto) (bool, error) {
	logger := global.TYD_LOGGER
	works := []model.Works{}
	db := o.DB
	worksInfo := db.Where("id IN ?", param.Ids).Where("member_id=?", o.MemberInfo.ID).Find(&works)
	if worksInfo.RowsAffected == 0 {
		logger.Error("作品数据不存在")
		return false, errors.New("作品数据不存在")
	}
	db.Delete(&works)
	return true, nil
}

//分页列表
func (o *WorksService) ListForPage(param dto.WorksListDto) *paginator.Pagination {
	//logger := global.TYD_LOGGER
	db := o.DB.Model(&model.Works{})
	worksList := []model.Works{}

	if param.Keyword != "" {
		db = db.Where("title like ?", "%"+param.Keyword+"%")
	}
	if param.Status > 0 {
		db = db.Where("status =?", param.Status)
	}
	db = db.Where("member_id=?", o.MemberInfo.ID)

	var total int64
	db.Count(&total)
	db.Scopes(paginator.Paginate(&param.PageParam)).Find(&worksList)
	result := &paginator.Pagination{}
	result.Page = param.Page
	result.PageSize = param.PageSize
	result.Total = total
	result.Data = worksList

	return result
}

func (o *WorksService) Edit(param dto.WorksEditDto) (bool, error) {
	logger := global.TYD_LOGGER
	works := model.Works{}
	db := o.DB
	worksInfo := db.Where("id = ?", param.ID).Where("member_id=?", o.MemberInfo.ID).First(&works)
	if errors.Is(worksInfo.Error, gorm.ErrRecordNotFound) {
		return false, errors.New("作品数据不存在")
	}
	works.Title = param.Title
	works.Cover = param.Cover
	works.Status = param.Status
	save := db.Select("title", "cover", "status").Save(&works)

	if save.Error != nil {
		logger.Error("数据更新失败")
		return false, save.Error
	}
	return true, nil
}
